import React, { useEffect, useState, Fragment } from 'react';
import { connect } from 'umi';
import { Card, Form, Button, message, ConfigProvider } from 'antd';
import moment from 'moment';
import { history } from 'umi';
import { formItemLayout } from '@/components/UserForm';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import SlidedTabs from '@/components/SlideTabs';
import { findCountry } from '@/pages/RecruitManage/PositionManage/part/utils';
import PersonInfo from '@/components/PersonInfo';
import ViewRecord from '@/pages/MyRecruit/Candidate/DetailResume/ViewRecord';
import { withRoutePage } from '@/utils/enhanceUtils';

import PageRouter from '@/components/PageRouter/PageRouter';
import pageTabUtil from '@/utils/pageTabUtil';

import { findIdentity } from './dict';
import Conclusion from './Components/Conclusion';
import PlanForm from './Components/PlanForm';
import InfoFrom from './Components/InfoFrom';
import styles from './TerviewList.less';

// 状态色
const dictColor = {
    applying: 'blue', // 申请中
    apply_failed: 'red', // "申请未通过"
    apply_success: 'green', // 申请通过
    be_pending: 'blue', // 待定
    eliminated: 'red', // 淘汰
    entry_cancel: 'red', // 取消入职
    entry_success: 'green', // 已入职
    offer_accepted: 'blue', // 已接受
    offer_refused: 'red', // 已拒绝
    offer_sended: 'blue', // 已发送
    pass: 'green', // 通过
    wait_for_beginning: '', // "待开始"
    wait_for_processing: '' // 待处理
};
const EditInterview = ({ loading, dispatch, form, user, interview, ...rags }) => {
    const User = user.currentUser; // 登陆人信息
    const [candidate, setCandidate] = useState('');
    const [interviewUser, setinterviewUser] = useState('');
    const [isEdit, setisEdit] = useState(true);
    const { interviewRecordList } = interview;
    const [interviewimage, setinterviewimage] = useState('');
    const [cancelReasonType, setCancelReasonType] = React.useState(''); // 区分进入详情面试结果的展示形式
    const [showBtn, setShowBtn] = React.useState(true); // 控制面试编辑按钮在已取消情况下不展示
    // 文件信息
    const [showFileList, setShowFileList] = useState([]);
    const [uploadResource, setUploadResource] = useState(null);
    // 获取改页面的身份 很多按钮的判断都是根据这个身份去显示
    // 考虑到消息提醒的时候，地址是不变的，这里做特殊判断，假如分数为空，则为按照之前来，否则必定显示面试详情结论页
    const dictList = findIdentity(
        typeof interviewUser.interviewScore !== 'number' ? rags.location.query.type : 'type4'
    );
    const { identity = '', tabs = [], conclusionDisable = true } = dictList;

    // 没有这个key会报错
    const tabsKey = tabs.length ? tabs.map(item => item.label).join('-') : 'tabsKey';
    // SlidedTabs
    const [activeKey, setActiveKey] = useState('1');

    const getPayload = type => {
        const values = form.getFieldsValue();
        const payload = {
            interviewArrangeCode: type === 'updata' ? rags.location.query.arrangeCode : '', // 面试安排code （从面试详情页发起时传）
            interviewConclusion: interviewUser.interviewConclusion,
            candidateCode: candidate.candidateCode,
            companyId: candidate.companyId,
            interviewEmployeeCode: values.interviewEmployeeId,
            interviewLeaderId: values.interviewLeaderId,
            interviewLocation: values.interviewLocation,
            interviewRemark: values.interviewRemark,
            interviewTime: values.time.format(
                `${moment(values.time, 'YYYY-MM-DD').format('YYYY-MM-DD')} ${values.timeValue}:00`
            ),
            interviewType: values.interviewType,
            interviewWay: values.interviewWay
        };
        return payload;
    };
    const handleSubmit = e => {
        e.preventDefault();
        form.validateFields(err => {
            if (!err) {
                dispatch({
                    type: 'interview/savefistinterview',
                    payload: getPayload(),
                    callback: res => {
                        if (res.code === 10000) {
                            message.success(res.msg);
                            pageTabUtil.goBack();
                        } else {
                            message.error(res.msg);
                        }
                    }
                });
            }
        });
    };

    // 预览面试评分表
    const previewImage = postType => {
        dispatch({
            type: 'interview/getinterviewimage',
            payload: {
                postType
            },
            callback: res => {
                setinterviewimage(res.url);
            }
        });
    };
    // 候选人查询
    const candidateSearch = code => {
        dispatch({
            type: 'interview/getinterviewrecruitinfo',
            payload: {
                arrangeCode: code
            },
            callback: res => {
                const { postTypeRemark = 'GroupRecruitPostType' } = findCountry(res.companyId);
                const zhiji = {
                    postTypeRemark,
                    postType: res.postType,
                    postRank: res.postRank
                };
                form.setFieldsValue({
                    talentName: res.talentName,
                    talentPhone: res.talentPhone,
                    recruitPost: res.recruitPost,
                    departmentName: res.departmentName,
                    postType: res.postType,
                    projectGroup: res.projectGroup,
                    resourceRelation: res.interviewFile,
                    talentAreaCode: res.talentAreaCode,
                    postGradeCode: res.postGradeCode,
                    zhiji
                });
                setCandidate(res);
                previewImage(res.recruitPostId);
            }
        });
    };
    // 根据候选人id获取面试安排数据
    const getinterviewinfo = code => {
        dispatch({
            type: 'interview/getinterviewinfo',
            payload: {
                arrangeCode: code
            },
            callback: res => {
                // 处理附件显示问题
                const { interviewFile = [] } = res;
                const resTime = res.interviewTime.split(/\s+/);
                setCancelReasonType(res.cancelReason);
                setShowBtn(res.cancelReason);
                setShowFileList(
                    interviewFile.map(item => {
                        const { keyName, originName, url } = item;
                        const itemRetrun = {
                            uid: keyName,
                            keyName,
                            name: originName,
                            oldName: originName,
                            url
                        };
                        return itemRetrun;
                    })
                );
                // 写入表单数据
                form.setFieldsValue({
                    interviewEmployeeCode: res.interviewEmployeeCode,
                    interviewLeaderId: res.interviewLeaderId,
                    interviewType: res.interviewType,
                    interviewWay: res.interviewWay,
                    time: moment(resTime[0]),
                    timeValue: resTime[1].slice(0, 5),
                    // interviewTime: res.interviewTime ? moment(res.interviewTime) : '',
                    interviewLocation: res.interviewLocation,
                    interviewRemark: res.interviewRemark,
                    interviewScore: res.interviewScore,
                    cancelReason: res.cancelReason,
                    cancelReasonRemark: res.cancelReasonRemark,
                    interviewConclusion:
                        res.interviewConclusion === 'wait_for_beginning' ? 'pass' : res.interviewConclusion,
                    postLevel: res.postType,
                    postLevel2: res.postLevel,
                    interviewSummary: res.interviewSummary
                });
                // 保存一份面试安排信息
                setinterviewUser(res);
                // 面试安排按钮判断
                setisEdit(true);
            }
        });
    };
    // 面试安排取消编辑
    const onResetPlan = () => {
        getinterviewinfo(rags.location.query.arrangeCode);
    };
    // 面试安排保存
    const onSavePlan = () => {
        form.validateFields(err => {
            if (!err) {
                dispatch({
                    type: 'interview/updateinterviewarrange',
                    payload: getPayload('updata'),
                    callback: res => {
                        if (res.code === 10000) {
                            onResetPlan();
                            message.success(res.msg);
                            setisEdit(true);
                        } else {
                            message.error(res.msg);
                        }
                    }
                });
            }
        });
    };
    // 获取候选人详情-筛选面试记录
    const fetchInterviewRecord = code => {
        dispatch({
            type: 'interview/fetchInterviewRecord',
            payload: {
                candidateCode: code
            }
        });
    };
    // 面试安排编辑
    const onEdit = () => {
        setisEdit(!isEdit);
    };
    // 上传组件change事件
    const setFileResource = (showFileListReturn, uploadResourceReturn) => {
        setShowFileList(showFileListReturn);
        setUploadResource(uploadResourceReturn);
    };

    // 身份为进行中面试的取消按钮
    const cancelBtnIng = () => {
        pageTabUtil.goBack();
    };
    // 保存面试结果
    const saveConclusion = () => {
        // const values = form.getFieldsValue();
        form.validateFields(
            [
                'interviewScore',
                'interviewConclusion',
                'postLevel',
                'postLevel2',
                'interviewSummary',
                'resourceRelation'
            ],
            (err, values) => {
                if (!err) {
                    // 附件需要特殊处理
                    const resourceRelationArr = [];
                    if (uploadResource) {
                        resourceRelationArr.push(uploadResource);
                    }
                    const payload = {
                        candidateCode: candidate.candidateCode,
                        interviewConclusion: values.interviewConclusion,
                        interviewRecordCode: interviewUser.interviewRecordCode,
                        interviewScore: values.interviewScore,
                        interviewSummary: values.interviewSummary,
                        postLevel: values.postLevel2,
                        postType: values.postLevel,
                        recordId: interviewUser.recordId,
                        resourceRelation: resourceRelationArr,
                        interviewType: interviewUser.interviewType,
                        interviewArrangeCode: interviewUser.interviewArrangeCode
                    };
                    dispatch({
                        type: 'interview/saveinterviewrecord',
                        payload,
                        callback: res => {
                            if (res.code === 10000) {
                                message.success(res.msg);
                                pageTabUtil.goBack();
                                // history.push('/personal/portal/recruit/interview');
                            } else {
                                message.error(res.msg);
                            }
                        }
                    });
                }
            }
        );
    };
    // 发起offer
    const getOffer = () => {
        dispatch({
            type: 'interview/featchApply',
            payload: {
                companyId: candidate.companyId
            },
            callback: res => {
                history.push({
                    pathname: '/personal/portal/flow/mine/list/apply',
                    query: {
                        action: 'edit',
                        formDeploymentId: res.formDeploymentId,
                        processDeploymentId: res.processDeploymentId,
                        templateId: res.id,
                        templateName: res.templateName,
                        talentId: candidate.candidateCode,
                        talentName: candidate.talentName
                    }
                });
            }
        });
    };
    const getPathName = () => rags.route.name;
    // 发起新面试
    const addInterview = () => {
        history.push({
            pathname:
                getPathName() === 'admineditinterview'
                    ? '/office/personnelManagement/recruit/interview/add'
                    : '/personal/portal/recruit/interview/add',
            query: {
                type: 'type0',
                candidateCode: candidate.candidateCode
            }
        });
    };
    // 根据身份判断编辑页面右上角的按钮菜单
    const getPersonInfoBtn = (conclusionDisables, showBtns) => {
        if (!conclusionDisables && !showBtns) {
            return [
                <Button
                    onClick={() => {
                        cancelBtnIng();
                    }}
                >
                    取消
                </Button>,
                <Button
                    loading={loading.effects['interview/saveinterviewrecord']}
                    type="primary"
                    onClick={() => {
                        saveConclusion();
                    }}
                >
                    保存
                </Button>
            ];
        }
        if (
            interviewUser.interviewLeaderId === User.id ||
            rags.location.pathname === '/office/personnelManagement/recruit/interview/edit'
        ) {
            // 先判断当前简历管理人是否为登陆人
            // 企业管理进来的面试管理记录都是可以编辑的
            // 经过这两个判断后，再取后端的判断条件
            const btnArr = [];
            if (candidate.isOffer) {
                btnArr.push(
                    <Button
                        disabled={candidate === ''}
                        type="primary"
                        onClick={() => {
                            getOffer();
                        }}
                    >
                        offer申请
                    </Button>
                );
            }
            if (candidate.isInterview) {
                btnArr.push(
                    <Button
                        disabled={candidate === ''}
                        type="primary"
                        onClick={() => {
                            addInterview();
                        }}
                    >
                        发起新面试
                    </Button>
                );
            }
            return btnArr;
        }
        return '';
    };
    const getSexName = key => {
        if (key === '1') {
            return 'man';
        }
        if (key === '2') {
            return 'woman';
        }
        return '';
    };
    // 详情页根据列表点击进来，获取候选人id和arrangeCode去获取请求数据
    useEffect(() => {
        if (rags.location.query.code) {
            candidateSearch(rags.location.query.code);
            fetchInterviewRecord(rags.location.query.code);
            getinterviewinfo(rags.location.query.arrangeCode);
        }
    }, []);
    // useEffect(() => {

    // }, []);
    return (
        <PageHeaderWrapper>
            <PageRouter type="myrecruit" activePath="/personal/portal/recruit/interview">
                <Form layout="horizontal" {...formItemLayout} onSubmit={handleSubmit}>
                    <Card bordered={false} style={{ padding: '24px 0', margin: 0 }} bodyStyle={{ padding: 0 }}>
                        <PersonInfo
                            style={{ padding: '0 24px' }}
                            sex={getSexName(candidate.talentSex)}
                            name={`${candidate.talentName ? candidate.talentName : ''}---${
                                candidate.recruitPost ? candidate.recruitPost : ''
                            }`}
                            status={`${candidate.candidateStageValue}-${candidate.candidateStateValue}`}
                            color={dictColor[candidate.candidateState]}
                            infos={[
                                {
                                    label: '招聘负责',
                                    value: interviewUser.interviewLeaderName
                                },
                                {
                                    label: '面试官',
                                    value: interviewUser.interviewEmployeeName
                                }
                            ]}
                            btns={getPersonInfoBtn(conclusionDisable, showBtn)}
                        />
                        <SlidedTabs
                            key={tabsKey}
                            cardStyle={{
                                height: 'calc(100vh - 400px)',
                                marginRight: 4,
                                padding: 0
                            }}
                            tabs={tabs}
                            activeKey={activeKey}
                            onChange={key => setActiveKey(key)}
                        >
                            {refs => (
                                <Fragment>
                                    <div ref={refs[0].ref} className="form-Wrap">
                                        <ConfigProvider getPopupContainer={trigger => trigger.parentNode}>
                                            <InfoFrom
                                                form={form}
                                                resourceRelation={candidate.talentFile}
                                                onCandidateSearch={code => {
                                                    candidateSearch(code);
                                                }}
                                                candidate={candidate}
                                                dictList={dictList}
                                                pathname={getPathName()}
                                            />
                                        </ConfigProvider>
                                    </div>
                                    <div className={styles.line} />
                                    <div ref={refs[1].ref}>
                                        <ConfigProvider getPopupContainer={trigger => trigger.parentNode}>
                                            <PlanForm
                                                form={form}
                                                user={User}
                                                onResetPlan={onResetPlan}
                                                onSavePlan={onSavePlan}
                                                onEdit={onEdit}
                                                isEdit={isEdit}
                                                dictList={dictList}
                                                candidate={candidate}
                                                interviewimage={interviewimage}
                                                pathname={getPathName()}
                                            />
                                        </ConfigProvider>
                                    </div>
                                    {identity === 'apply' ? (
                                        ''
                                    ) : (
                                        <Fragment>
                                            <div className={styles.line} />
                                            <div ref={refs[2].ref} className="form-Wrap">
                                                <ConfigProvider getPopupContainer={trigger => trigger.parentNode}>
                                                    <Conclusion
                                                        form={form}
                                                        user={User}
                                                        candidate={candidate}
                                                        showFileList={showFileList}
                                                        uploadResource={uploadResource}
                                                        onSetFileResource={setFileResource}
                                                        dictList={dictList}
                                                        interviewimage={interviewimage}
                                                        cancelReasonType={cancelReasonType}
                                                    />
                                                </ConfigProvider>
                                            </div>
                                            <div className={styles.line} />
                                            <div ref={refs[3].ref}>
                                                <h3 className="vv-from-title">面试记录</h3>
                                                <ViewRecord
                                                    companyId={candidate.companyId}
                                                    tableData={interviewRecordList}
                                                />
                                            </div>
                                        </Fragment>
                                    )}
                                </Fragment>
                            )}
                        </SlidedTabs>
                    </Card>
                </Form>
            </PageRouter>
        </PageHeaderWrapper>
    );
};
export default withRoutePage(
    connect(({ loading, user, interview }) => ({
        interview,
        user,
        loading
    }))(Form.create()(EditInterview))
);
